﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using bmapi.HelperClass;
using bmapi.Models.DataEntity;

namespace bmapi.Controllers
{
    public class CADStyleController : CADApplyController
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="id">流程id</param>
        /// <returns></returns>
        [HttpPost, Route("cadStyle/Apply")]
        public string Apply(int id)
        {
            WriteLog("cadStyle/Apply", "id:"+ id, true);

            //登陆者login_id 
            //id实际是token   
            User user = GetUserByLoginID(GetCrrentIDByToken());
            #region 允许特体处理多工序 优先特体
            if (user != null)
            {
                //暂时取消排料工序  
                user = SuitProcess(user, false);
                WriteDebug("cadStyle/Apply-0704", "我的所有工序:code-" + user.code + ",code2-" + user.code2 + ",code3-" + user.code3);
                if (user.code == 35 || user.code2 == 35 || user.code3 == 35)
                {
                    string res = PodTask(id, user);
                    WriteDebug("特体", res);
                    if (res == null) //没有特体 
                        return Task(user, id);
                    return res;
                }
                else  //用户不处理特体 
                    return Task(user,id);               
            }
            else
                return ReturnError(201, "不合法的用户");

            #endregion

        }
        /// <summary>
        /// 特体处理 
        /// </summary>
        /// <param name="id"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        private string PodTask(int id, User user)
        {
            WriteDebug("PodTask", "特体任务申请");
            PC pc = null;
            if (id != 0)
            {
                pc = GetPC(id,35);
                if (pc == null) //return ReturnOK(0, 0, "");//没有合适任务
                    return null;
                else
                    return ReturnOK(pc.pc_id, pc.step, pc.path);
            }
            PidOid pod = LockPod(user);
            if (pod == null) //return ReturnOK(0, 0, "", 0);//没有合适任务
                return null;
            else
                /*PC pc = null; *///需要联合查询 
                return ReturnOK(pod.OrderId, 35, pod.PcName, pod.Pod);
        }

        /// <summary>
        /// 驱动任务
        /// </summary>
        /// <param name="user"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        private string Task(User user,int id)
        {
            WriteDebug("cadStyle/Apply", "id--"+id);
            PC pc = null;
            if (id != 0)
                pc = GetPC(id);
            else
                pc = LockTask(user, IsOrder(user.code));
            if (pc == null)
            {
                WriteDebug("cadStyle/Apply", "没有驱动任务");
                return ReturnOK(0, 0, "");
            }
            else
            {
                WriteDebug("cadStyle/Apply", "驱动任务" + pc.pc_id);
                if (id == 0)
                    AddTask(pc.step, pc.pc_id);
                if (pc.step == 33)
                    CreateOrderWorkPath(pc.path);
                return ReturnOK(pc.pc_id, pc.step, pc.path);
            }
        }
        /// <summary>
        /// 申请是创建工作目录(批量导入的处理)
        /// </summary>
        /// <param name="name"></param>
        private void CreateOrderWorkPath(string name)
        {
            string dir = m_buyiRoot + "\\buyiwork\\"+ name;
            if (!Directory.Exists(dir))
                Directory.CreateDirectory(dir);
        }


        [HttpGet, Route("cadStyle/ReDownLoad")]
        public string ReDownload()
        {
            try
            {
                WriteDebug("cadStyle/ReDownLoad", "进入打版重新下载");
                //这个接口用来解决打版重新下载问题   
                User user = GetUserByLoginID(GetCrrentIDByToken());
                if (user == null)
                {
                    WriteDebug("cadStyle/ReDownLoad", "无法检测到当前用户");
                    return ReturnPCList(null);
                }
                else
                {
                    //暂时取消打版工序 因为排料不能再打版中做 step=@ucode or step=@ucode2 or step=@ucode3
                    user = SuitProcess(user, false);
                    WriteDebug("cadStyle/ReDownLoad", "我的所有工序:code-" + user.code + ",code2-" + user.code2 + ",code3-" + user.code3);
                    if (user.code == 35 || user.code2 == 35 || user.code3 == 35)
                    {
                        string res = ReloadPod(user);
                        if (res == null)
                            return ReloadTask(user);
                        return res;
                    }
                    else
                        return ReloadTask(user);
                }
            }
            catch (Exception ex)
            {
                WriteDebug("ReDownload", "异常："+ex.Message);
                return ReturnPCList(null); 
            }
           
        }

        /// <summary>
        /// 重新下载特体
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        private string ReloadPod(User user)
        {
            try
            {
                WriteDebug("ReloadPod", "检查特体任务");
                string sql = "select pod_id as PodId ,Pod_tb.Pod,Pod_tb.time as Time, PC_tb.pc_id as OrderId, PC_tb.path as PcName,model_id as ModelId from Pod_tb join PC_tb on Pod_tb.order_id=PC_tb.pc_id where user_id=@loginid and state=0 order by Pod_tb.time desc";
                SQLCommand sc = new SQLCommand(sql, "@loginid", user.login_id);
                DataTable dt = sc.ExecuteScalars();
                if (dt == null)  // return ReturnPodList(null);
                    return null;
                else
                {
                    List<PidOid> pod = AssistFun.DataTableToList<PidOid>(dt);
                    WriteDebug("ReDownLoad2", "特体数:" + pod.Count);
                    return ReturnPodList(pod);
                }
            }
            catch (Exception ex)
            {
                WriteDebug("ReloadPod", "异常："+ex.Message);
                return null;
            }
           
        }

        /// <summary>
        /// 重新下载驱动任务
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        private string ReloadTask(User user)
        {
            WriteDebug("cadStyle/ReDownLoad", "没有特体任务");
            SQLCommand sc = new SQLCommand("select PC_tb.* from PC_tb join order_tb on pc_id=id where station=@loginid and (step=@ucode or step=@ucode2 or step=@ucode3) and download=1 and (PC_tb.bind_id=0 or Order_tb.bind_id=pc_id) order by order_tb.rank desc,order_tb.finish_time asc");
            sc.Add("@loginid", user.login_id);
            sc.Add("@ucode", user.code == 35 ? 0 : user.code); //申请特体以外的打版任务 
            sc.Add("@ucode2", user.code2 == 35 ? 0 : user.code2);
            sc.Add("@ucode3", user.code3 == 35 ? 0 : user.code3);
            DataTable dt = sc.ExecuteScalars();
            if (dt == null) //没有除特体外的打版任务 
            {
                WriteDebug("cadStyle/ReDownLoad", "没有打版任务");
                return ReturnPCList(null);
            }
            else
            {
                WriteDebug("cadStyle/ReDownLoad", "有驱动任务");
                List<PC> pc = AssistFun.DataTableToList<PC>(dt);
                return ReturnPCList(pc);
            }
        }

        /// <summary>
        /// 检查是否有适合的任务
        /// </summary>
        /// <returns></returns>
        [HttpGet, Route("cadStyle/FindTask")]
        public string FindTask()
        {
            //当前登录者   用于定时刷新
            User user = GetUserByLoginID(GetCrrentIDByToken());
            user = SuitProcess(user, false);
            if (user.code != 35)
                return CheckIsHavePC(user).ToString();
            else
                return CheckIsHavePod(user).ToString(); ;

        }

        /// <summary>
        /// 寻找待分配的特体检查任务
        /// </summary>
        /// <param name="u"> 用户 </param>
        protected int CheckIsHavePod(User u)
        {
            int rtn = 0;
            string sql = "";
            sql = "select category_name from CategoryUser_tb where login_id=@loginid";
            SQLCommand sc = new SQLCommand(sql, "@loginid", u.login_id);
            if (sc.ExecuteScalar() == null)
            {
                sql = "select count(*) from Pod_tb join PC_tb on Pod_tb.order_id=PC_tb.pc_id where user_id=0 and PC_tb.PLID=@plid ";
                sc = new SQLCommand(sql, "@plid", u.PLID);
                rtn = Convert.ToInt32(sc.ExecuteScalar());
            }
            else
            {
                sql = "select count(pc_id) from Order_tb join PC_tb on Order_tb.id=PC_tb.pc_id where PC_tb.PLID=@plid and PC_tb.model_id in ( select style_id from Style_tb where type in(select category_name from CategoryUser_tb where login_id = @loginid) )";
                sc = new SQLCommand(sql);
                sc.Add("@loginid", u.login_id);
                sc.Add("@plid", u.PLID);
                rtn = Convert.ToInt32(sc.ExecuteScalar());
            }
            //sql = "select count(*) from Pod_tb join PC_tb on Pod_tb.order_id=PC_tb.pc_id where user_id=0 and PC_tb.PLID=@plid ";
            //SQLCommand sc = new SQLCommand(sql);
            //sc.Add("@plid", u.PLID);
            //int rtn = Convert.ToInt32(sc.ExecuteScalar());
            return rtn;
        }

        /// <summary>
        /// 锁定待分配的特体检查任务
        /// </summary>
        /// <param name="u"> 用户 </param>
        protected PidOid LockPod(User u)
        {
            WriteDebug("LockPod", "锁定待分配的特体检查任务");
            PidOid pod = null;
            for (int i = 0; i < 5; i++)
            {
                string sql = "";
                if (SQLCommand.IsOracle)
                    sql = "select pod_id as PodId,a.Pod,a.time as Time,a.pc_id as OrderId,a.path as PcName,model_id as ModelId from(select pod_id,pod,time,pc_id,path,model_id from Pod_tb join PC_tb on Pod_tb.order_id = PC_tb.pc_id where user_id = 0 and PC_tb.PLID = @plid order by rank desc, time desc) a where rownum = 1 ";
                //sql = "select pod_id as PodId,Pod_tb.Pod,Pod_tb.time as Time,PC_tb.pc_id as OrderId,PC_tb.path as PcName from Pod_tb join PC_tb on Pod_tb.order_id=PC_tb.pc_id where rownum<2 and user_id=0 and PC_tb.PLID=@plid order by time desc"; 
                else
                    sql = "select top 1 pod_id as PodId,Pod_tb.Pod,Pod_tb.time as Time,PC_tb.pc_id as OrderId,PC_tb.path as PcName,model_id as ModelId from Pod_tb join PC_tb on Pod_tb.order_id=PC_tb.pc_id where user_id=0 and PC_tb.PLID=@plid order by rank desc, time desc";

                SQLCommand sc = new SQLCommand(sql, "@plid", u.PLID);
                DataRow dr = sc.ExecuteOneRow();
                if (dr == null)
                    break;
                else
                {
                    pod = AssistFun.DataRowToObject<PidOid>(dr);
                    if (!SuitMyPod(u.login_id, pod.ModelId))  //有特体任务  但是不适合我
                        return null;
                    //有特体任务修改pod  user_id=当前loginid 
                    sql = "update Pod_tb set user_id=@userid,time=@time where pod_id=@pid and user_id=0";
                    if (SQLCommand.IsOracle)
                        sql = "update Pod_tb set user_id=@userid,time=to_date(@time,'yyyy-mm-dd hh24:mi:ss') where pod_id=@pid and user_id=0";
                    sc = new SQLCommand(sql);
                    sc.Add("@userid", u.login_id);
                    sc.Add("@time", DateTime.Now, true);
                    sc.Add("@pid", pod.PodId);
                    int rtn = sc.ExecuteNonQuery();
                    if (rtn == 1)
                        return pod;
                }
            }
            WriteDebug("LockPod", "没有特体检查任务");
            return pod;
        }
    }
}
